package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressMapper;
import com.sky.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public void save(AddressBook addressBook) {

        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressMapper.save(addressBook);
    }

    @Override
    public List<AddressBook> list(AddressBook addressBook) {
        List<AddressBook>list=addressMapper.list(addressBook);
        return list;
    }

    @Override
    public AddressBook getById(Long id) {
        AddressBook addressBook=addressMapper.getById(id);
        return addressBook;
    }

    @Override
    public void update(AddressBook addressBook) {
        addressMapper.update(addressBook);
    }

    @Transactional
    public void setDefault(AddressBook addressBook) {
        //将当前所有地址改为非默认地址
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressMapper.updateIsDefaultByUserId(addressBook);
        //将当前地址改为默认地址
        addressBook.setIsDefault(1);
        addressMapper.update(addressBook);
    }

    @Override
    public void deleteById(Long id) {
        addressMapper.deleteById(id);
    }
}
